<?php
	require_once '../common/dao.php';
	
	$action = $_GET["action"];
	
	if(!preg_match("/^[a-z]+$/D", $action))
	{
		throw new Exception("Invalid Arguments.");
	}
	
	switch($action)
	{
		case "create":
			$userID = $_POST["txtUserID"];
			$password = "";
			$FirstName = $_POST["txtFirstName"];
			$LastName = $_POST["txtLastName"];
			$RoleID = $_POST["selRol"];
			
			createUser($userID, $password, $FirstName, $LastName, $RoleID);
			
			header('Location: operadmin.php');
			break;
		case "delete":
			$userID = $_POST["txtUserID"];
			
			deleteUser($userID);
			
			break;
		case "edit":
			$userID = $_POST["hidOperID"];
			$FirstName = $_POST["txtFirstName"];
			$LastName = $_POST["txtLastName"];
			$RoleID = $_POST["selRol"];
			$Active = $_POST["optActive"];
			
			editUser($userID, $FirstName, $LastName, $RoleID, $Active);
			
			header('Location: operadmin.php');
			break;
		case "changepwd":
		
			break;
	}
		
	function editUser($pUserID, $pFirstName, $pLastName, $pRoleID, $pActive)
	{
		//Validate user input here
		
		$strSQL = "UPDATE tbl_Operator";
		$strSQL .= " SET FirstName = '" . $pFirstName . "',";
		$strSQL .= " LastName = '" . $pLastName . "',";
		$strSQL .= " RoleID = " . $pRoleID . ",";
		$strSQL .= " IsActive = " . $pActive;
		$strSQL .= " WHERE OperatorID = '" . $pUserID . "'";
		
		DAO::run_non_query($strSQL);
	}
	
	function createUser($pUserID, $pPassword, $pFirstName, $pLastName, $pRoleID)
	{
		//Validate user input here
		
		//Does OperatorID already exists?
		settype($pUserID, 'string');
		$strSQL = sprintf("SELECT COUNT(OperatorID) AS N FROM tbl_Operator WHERE OperatorID = '%s';", $pUserID);
		$result = DAO::run_query($strSQL);
		$row = mysql_fetch_row($result);
		if($row[0] > 0) {
			throw new Exception('El Operador ya existe.');
		}
		mysql_free_result($result);
		
		$strSQL = "INSERT INTO tbl_Operator(OperatorID, Password, FirstName, LastName, RoleID, IsActive)";
		$strSQL .= " VALUES ('" . $pUserID . "','" . $pPassword . "','" . $pFirstName . "','";
		$strSQL .= $pLastName . "'," . $pRoleID . ",1);";
		
		DAO::run_non_query($strSQL);
	}
	
	function deleteUser($pUserID)
	{
		//Validate user input here
		
		$strSQL = "UPDATE tbl_Operator SET IsActive = 0 WHERE OperatorID = '" . $pUserID . "';";
		
		DAO::run_non_query($strSQL);
	}
?>